<template>
    <div v-if="true" class="flex-grow"></div>    
    <el-sub-menu v-if="true" index="">
        <template #title>
            <el-icon><UserFilled /></el-icon>{{userInfo.realName}}
        </template>
        <!-- <el-menu-item v-if="isAdmin" index="/bi_frontend/userMgt" @click="handleMenuClick">用户管理</el-menu-item>
        <el-menu-item index="" @click="userInfoEditDialog()">我的信息或密码修改</el-menu-item> -->
        <el-menu-item index="" @click="logoutDialog()">退出</el-menu-item>
    </el-sub-menu>

    <!-- 编辑配置 -->
    <el-dialog v-model="userInfoEditVisible" title="信息修改">
        <el-form ref="ruleEditFormRef" :model="editObj.form" :rules="editObj.form_rules" label-width="90px">
            <el-form-item label="用户ID" prop="id">
                <el-input disabled v-model="editObj.form.id" />
            </el-form-item>
            <el-form-item  label="姓名" prop="realName">
                <el-input :disabled="realNameVisible" v-model="editObj.form.realName" />
            </el-form-item>
            <el-form-item label="原密码" prop="origPw">
                <el-input type="password" show-password v-model="editObj.form.origPw" />
            </el-form-item>
            <el-form-item label="新密码" prop="password">
                <el-input type="password" show-password v-model="editObj.form.password" />
            </el-form-item>
            <el-form-item label="确认新密码" prop="passwords">
                <el-input type="password" show-password v-model="editObj.form.passwords" />
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input type="mobile" v-model="editObj.form.mobile" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="userInfoEditVisible = false">取消</el-button>
                <el-button type="primary" :disabled="editObj.submit_button_disabled" @click="editUser(ruleEditFormRef)">确认</el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog v-model="logoutVisible" title="确定要退出登录吗？">
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="logoutVisible = false">取消</el-button>
                <el-button type="primary" @click="logout">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
    import { ref,reactive,computed} from "vue";
    import { useRouter } from "vue-router";
    import { validate_password, validate_mobile } from "/src/utils/validate";
    import { ElMessage, FormInstance} from 'element-plus';
    import { GetById,UpdateUser} from "/src/api/account";
    import desPwd from "/src/utils/kjax.des";

    // const userInfo = reactive({id:'tUser'});

    // const userInfo = reactive({realName:localStorage.getItem('realName')});

    const userInfo = reactive({realName:'Admin'});

    const router = useRouter();

    const logoutVisible = ref(false);

    const realNameVisible = computed(() => {
        return localStorage.getItem('userId')=='Admin'?true:false;
    });

    // 弹出确认登出对话框
    const logoutDialog = ()=> {
        logoutVisible.value = true;
    }

    // 退出登录
    const logout = ()=> {
        localStorage.setItem('token', '');
        router.push("/bi_frontend");
        logoutVisible.value = false;
    }

    let  isAdmin = ref(false);

    isAdmin = localStorage.getItem('userId')=='Admin'?true:false;

    const userInfoEditVisible = ref(false);

    const ruleEditFormRef = ref<FormInstance>();

    
    // 定义发射给父组件的方法
    const emits = defineEmits(['savePath'])

    // 向外抛出菜单路径保存事件
    const handleMenuClick = () => {
        emits('savePath', '/bi_frontend/userMgt')
    }

    const validate_name_rules = (rule, value, callback) => {
		if (value === "") {
			callback(new Error("请输入姓名"));
		}else {
			callback();
		}
	};

    const validate_origPw_rules = (rule, value, callback) => {
        
        const passwordValue = editObj.form.password;

		if(!value && passwordValue){
            callback(new Error("请输入原密码."));
        }else{
            callback();
        }
	};

    const validate_password_rules_u = (rule, value, callback) => {
        let regPassword = validate_password(value);
        if(value){
            if (!regPassword) {
                // callback(new Error("请输入>=6并且<=20位的密码，包含数字、字母"));
                callback(new Error("请输入>=8并且<=20位的密码，包含数字、小写字母、大写字母、特殊字符 )(#?!@$%^&*-"));
            } else {
                ruleEditFormRef.value.validateField('passwords', () => null);
                ruleEditFormRef.value.validateField('origPw', () => null);
                callback();
            }
        }else{
            ruleEditFormRef.value.validateField('passwords', () => null);
            ruleEditFormRef.value.validateField('origPw', () => null);
            callback();
        }
	};
	// 校验确认密码
	const validate_passwords_rules_u = (rule, value, callback) => {
		
		let regPassword = validate_password(value);
		// 获取“密码”
		const passwordValue = editObj.form.password;

        if(value){
            if(!regPassword) {
                // callback(new Error("请输入>=6并且<=20位的密码，包含数字、字母"));
                callback(new Error("请输入>=8并且<=20位的密码，包含数字、小写字母、大写字母、特殊字符 )(#?!@$%^&*-"));
            }else if (passwordValue !== value) {
			    callback(new Error("两次密码不一致"));
            }else{
                callback();
            }
        }else{
            if(passwordValue){
                callback(new Error("两次密码不一致"));
            }else{
                callback();
            }
        }
	};

    // 校验手机号
	const validate_mobile_rules = (rule, value, callback) => {

        let regMobile = validate_mobile(value);
        if (value === "") {
            callback(new Error("请输入手机号"));
        } else if (!regMobile) {
            // callback(new Error("请输入>=6并且<=20位的密码，包含数字、字母"));
            callback(new Error("手机号不合法"));
        } else {
            callback();
        }
    };

     // 修改配置表单变量
     const editObj = reactive({
        form_rules: {
			realName: [{ validator: validate_name_rules, trigger: "change" }],
            origPw: [{ validator: validate_origPw_rules, trigger: "change" }],
			password: [{ validator: validate_password_rules_u, trigger: "change" }],
			passwords: [{ validator: validate_passwords_rules_u, trigger: "change" }],
            mobile: [{ validator: validate_mobile_rules, trigger: "change" }],
		},
        submit_button_disabled:false
    })
    // 弹出确认登出对话框
    const userInfoEditDialog = ()=> {

        GetById(localStorage.getItem('userId'))
            .then((res) => {
                // 编辑数据设置
                if(res.code === 200){
                    editObj.form = res.data
                    delete editObj.form.password;
                    // editObj.form.passwords = res.data.password;
                    // 打开弹出框
                    userInfoEditVisible.value = true;
                }else{
                    ElMessage({
						message: res.msg||'获取用户信息失败.',
						type: "eror",
					});
                }
            });
    }

    const editUser = (formEl: FormInstance | undefined) => {
        if (!formEl) return;
        formEl.validate((valid) => {

            if(!valid) {
                console.log(valid);
                return false;
            }
           
            // 禁用按钮
            editObj.submit_button_disabled = true;

            const requestData = {
                id: editObj.form.id,
                realName: editObj.form.realName,
                mobile: editObj.form.mobile,
            };

            if(editObj.form.password){
                requestData.password = desPwd.getDes(editObj.form.password.trim(), 'kingdom');
                requestData.origPw = desPwd.getDes(editObj.form.origPw.trim(), 'kingdom');
            }

            UpdateUser(requestData)
            .then((res) => {
                if(res.code === 200){
                    editObj.submit_button_disabled = false;
                    ElMessage({
                        message: '修改成功！',
                        type: 'success',
                    })
                    userInfoEditVisible.value = false;
                }else{
                    ElMessage({
						message: res.msg||'修改用户信息失败.',
						type: "eror",
					});
                    editObj.submit_button_disabled = false;
                }
            }).catch((error) => { 
                editObj.submit_button_disabled = false;
            });

        })
    }

</script>

<style scoped>
    .flex-grow {
        flex-grow: 1;
    }
</style>

